package bma.common.netty.tester;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelEvent;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelUpstreamHandler;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.UpstreamMessageEvent;

import bma.common.netty.handler.ChannelHandlerContextWrap;

public class ChannelHandlerDecoderTester implements ChannelUpstreamHandler {

	private ChannelUpstreamHandler decoder;

	public ChannelHandlerDecoderTester() {
		super();
	}

	public ChannelHandlerDecoderTester(ChannelUpstreamHandler decoder) {
		super();
		this.decoder = decoder;
	}

	public ChannelUpstreamHandler getDecoder() {
		return decoder;
	}

	public void setDecoder(ChannelUpstreamHandler decoder) {
		this.decoder = decoder;
	}

	@Override
	public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e)
			throws Exception {
		if (e instanceof MessageEvent) {
			MessageEvent msg = (MessageEvent) e;
			messageReceived(ctx, msg);
		}
		ctx.sendUpstream(e);
	}

	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
			throws Exception {

		Object m = e.getMessage();
		if (!(m instanceof ChannelBuffer)) {
			ctx.sendUpstream(e);
			return;
		}

		ChannelBuffer input = (ChannelBuffer) m;
		if (!input.readable()) {
			return;
		}
		ChannelBuffer newBuffer = input.copy();
		ChannelHandlerContextWrap newContext = new ChannelHandlerContextWrap(
				ctx) {

			@Override
			public void sendUpstream(ChannelEvent e) {
				// do nothing
				decodeObject(e);
			}

		};
		decoder.handleUpstream(
				newContext,
				new UpstreamMessageEvent(e.getChannel(), newBuffer, e
						.getRemoteAddress()));
	}

	public void decodeObject(ChannelEvent e) {

	}
}
